package com.neuedu.io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ObjectStreamDemo {
    public static void main(String[] args) {
        File  file= new File("d://obj.obj");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        User  u = new User(101,"张三","123456",20);
        User  u1 = new User(102,"张四","123456",20);
        User  u2 = new User(103,"张五","123456",20);
        User  u3 = new User(104,"张六","123456",20);
        User  u4 = new User(105,"张七","123456",20);

        try {
            ObjectOutputStream  oos = new ObjectOutputStream(new FileOutputStream(file));
            ObjectInputStream  ois  = new ObjectInputStream(new FileInputStream(file));

//            oos.writeObject(u);
//            oos.writeObject(u1);
//            oos.writeObject(u2);
//            oos.writeObject(u3);
//            oos.writeObject(u4);


//            for(int i= 0; i < 5;i++) {
//                User user = (User) ois.readObject();
//                System.out.println(user);
//            }
            List<User>  list = new ArrayList<>();
            list.add(u);
            list.add(u1);
            list.add(u2);
            list.add(u3);
            list.add(u4);
            oos.writeObject(list);
            List<User>  list2 =  (List<User>) ois.readObject();
            list2.forEach(x-> System.out.println(x));

            oos.close();
            ois.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

}
